﻿package caro_game;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class MayChu extends javax.swing.JFrame {

    ServerSocket Sv_socket;
    Socket s_ket;
    DataInputStream NhanDuLieu;
    DataOutputStream GuiDuLieu;
    String ip;
    
    boolean coMotHai = false;
    boolean coBatDau = true;

    public MayChu() {
        initComponents();
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        DS_CHAT = new javax.swing.JTextArea();
        lbTB = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lbTenMayChu = new javax.swing.JLabel();
        lbIPMayChu = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        DS_CHAT.setEditable(false);
        DS_CHAT.setColumns(20);
        DS_CHAT.setRows(5);
        jScrollPane1.setViewportView(DS_CHAT);

        lbTB.setText("   ");

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Tên");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("IP:");

        lbTenMayChu.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lbTenMayChu.setText("  ");

        lbIPMayChu.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lbIPMayChu.setText("  ");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N
        jLabel3.setText("THÔNG TIN SERVER");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbIPMayChu)
                            .addComponent(lbTenMayChu)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jLabel3))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(lbTB))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(35, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addComponent(jLabel3)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lbTenMayChu))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbIPMayChu)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbTB)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MayChu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MayChu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MayChu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MayChu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
//                new MayChu().setVisible(true);
            }
        });
        MayChu m = new MayChu();
        m.setVisible(true);
        m.KetNoi_MayKhach();
    }

    // Hàm kêt nối tới Máy khách.
    public void KetNoi_MayKhach() {
        try {

            InetAddress addr = InetAddress.getLocalHost();

            //Host IP Address
            String IpMayChu = addr.getHostAddress();
            //Hostname
            String TenMayChu = addr.getHostName();
            lbTenMayChu.setText(TenMayChu);
            lbIPMayChu.setText(IpMayChu);
            
            Sv_socket = new ServerSocket(123);//truyền cổng vaofn ha.
            s_ket = Sv_socket.accept();
            
            ip = s_ket.getInetAddress().getHostAddress();
            String ten = s_ket.getInetAddress().getHostName();
            
            lbTB.setText("Máy chủ đã sẵn sàng!");
            GuiDuLieu = new DataOutputStream((s_ket.getOutputStream()));
            NhanDuLieu = new DataInputStream(s_ket.getInputStream());
            int dem=0;
            while (true) {
                if (coMotHai == false)
                {
                    if(coBatDau==false){
                    Sv_socket = new ServerSocket(123);//truyền cổng vaofn ha.
                    s_ket = Sv_socket.accept();
                    ip = s_ket.getInetAddress().getHostAddress();//lấy ip của mấy khách
                    }
                    coBatDau=false;
                    Thread_Socket1 t = new Thread_Socket1(s_ket, DS_CHAT, NhanDuLieu, GuiDuLieu,"1",dem,ip);
                    t.start();
                    DS_CHAT.append("Cặp "+(dem+1)+": \n");
                    DS_CHAT.append("Server "+(dem+1)+": "+ten+"\n");
                    coMotHai = true;
                    Sv_socket.close();      //đóng kết nối.
                }
                else if (coMotHai == true)
                {
                    Sv_socket = new ServerSocket(123);//truyền cổng vaofn ha.
                    s_ket = Sv_socket.accept();
                    ip = s_ket.getInetAddress().getHostAddress();//lấy ip của mấy khách
                    Thread_Socket1 t = new Thread_Socket1(s_ket, DS_CHAT, NhanDuLieu, GuiDuLieu,"2",dem,ip);
                    t.start();
                    DS_CHAT.append("Client "+(dem+1)+": "+ten+"\n\n");
                    dem++;
                    coMotHai = false;
                    Sv_socket.close();
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(MayChu.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea DS_CHAT;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbIPMayChu;
    private javax.swing.JLabel lbTB;
    private javax.swing.JLabel lbTenMayChu;
    // End of variables declaration//GEN-END:variables
}

class Thread_Socket1 extends Thread
{
    Socket socket;
    JTextArea DS_CHAT;
    DataInputStream Doc_NhapVao;
    DataOutputStream GuiDuLieu;
    String cong;
    int dem;
    String ip;
    static String luuip;

    public Thread_Socket1(Socket sk, JTextArea DS_Chat,DataInputStream nhap, DataOutputStream GuiDuL, String c,int d,String ipp)
    {
        this.socket = sk;
        this.DS_CHAT = DS_Chat;
        this.Doc_NhapVao = nhap;
        this.GuiDuLieu = GuiDuL;
        this.cong = c;
        this.dem = d;
        this.ip = ipp;
    }
    public void run()
    {
        if(cong=="1")
        {
        try {
                luuip = ip;
                Doc_NhapVao = new DataInputStream(socket.getInputStream());
                GuiDuLieu = new DataOutputStream(socket.getOutputStream());
                
                if(dem<10){
                GuiDuLieu.writeBytes("1"+dem+"00a"+ "\n");
                }
                else if(dem < 100)
                {
                    GuiDuLieu.writeBytes("1"+dem+"0a"+ "\n");
                }
                else if(dem<1000)
                {
                    GuiDuLieu.writeBytes("1"+ dem +"a\n");
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Không gửi được!");
            }
        }
        else if(cong=="2")
        {
            try {
                Doc_NhapVao = new DataInputStream(socket.getInputStream());
                GuiDuLieu = new DataOutputStream(socket.getOutputStream());
                 if(dem<10){
                GuiDuLieu.writeBytes("1"+dem+"00"+ "\n");
                GuiDuLieu.writeBytes(luuip+ "\n");
                }
                else if(dem < 100)
                {
                    GuiDuLieu.writeBytes("1"+dem+"0"+ "\n");
                    GuiDuLieu.writeBytes(luuip+ "\n");
                }
                else if(dem<1000)
                {
                    GuiDuLieu.writeBytes("1"+ dem +"\n");
                    GuiDuLieu.writeBytes(luuip+ "\n");
                }
                else if(dem==1000)
                {
                    dem=0;
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Không gửi được!");
            }
        }
    }
}
